﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using LERP.Domain;
using LERP.Domain.Enums;
using LERP.Web.Controllers.ViewModels.ContractViewModels;
using Sharp.Framework;
using Sharp.Framework.Queries;
using SharpArch.NHibernate.Web.Mvc;

namespace LERP.Web.Controllers
{
    public class ContractController : Controller
    {

        private readonly IQuery _query;

        public ContractController(IQuery query)
        {
            this._query = query;
        }
 

        /// <summary>
        /// 获取合同列表
        /// </summary> 
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(string keyword, int page = 1, int size = 12)
        { 
            var query = _query.FindAll<Contract>().Where(m => m.Stauts == DataStatus.Normal);
            
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Subsidiary.Name.Contains(keyword) || m.Code.Contains(keyword));
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new ContractViewModel
            {
                Id = m.Id,
                BeginTime = m.BeginTime.ToString("yyyy-MM-dd"),
                Customer = m.Subsidiary.Id,
                CustomerName = m.Subsidiary.Name,
                EndTime = m.EndTime.ToString("yyyy-MM-dd"),
                Code = m.Code
            }).ToPagedList(page, size);

            return View(model);
        }
         

        /// <summary>
        /// 创建合同
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.Customers = GetCustomers();
            return View(new ContractViewModel
                            {
                                BeginTime = DateTime.Now.ToString("yyyy-MM-dd"),
                                EndTime = DateTime.Now.AddYears(1).ToString("yyyy-MM-dd")
                            });
        }
        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <returns></returns>
        private object GetCustomers()
        {
            return _query.FindAll<Subsidiary>().Where(m =>   m.Status == DataStatus.Normal).Select(
                m => new SelectListItem {Text = m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture)}).ToList();
        }

        /// <summary>
        /// 提交 新增合同
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult Create(ContractViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (_query.FindAll<Contract>().Any(x => x.Code == model.Code))
                    {
                        ModelState.AddModelError("Code", "合同编号已存在");
                        ViewBag.Customers = GetCustomers();
                        return View(); 
                    }

                    var entity = new Contract
                        { 
                            Stauts = DataStatus.Normal,
                            Created = DateTime.Now,
                            Modified = DateTime.Now, 
                            BeginTime = DateTime.Parse(model.BeginTime), 
                            EndTime = DateTime.Parse(model.EndTime),
                            Code = model.Code
                        };
                    var customer = _query.Get<Subsidiary>(model.Customer);
                    if (null == customer)
                    {
                        ModelState.AddModelError("Customer", "客户不存在,请重新选择");
                        ViewBag.Customers = GetCustomers();
                        return View();
                    }
                    entity.Subsidiary = customer;
                    _query.Save(entity);
                    return RedirectToAction("Index", "Contract");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            ViewBag.Customers = GetCustomers();
            return View(model);
        }

       /// <summary>
       /// 修改合同
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var m = _query.Get<Contract>(id);
            if (null == m)
            {
                return View("NoFound");
            }
            var contract = new ContractViewModel
               {
                   BeginTime = m.BeginTime.ToString("yyyy-MM-dd"),
                   Customer = m.Subsidiary.Id,
                   CustomerName = m.Subsidiary.Name,
                   EndTime = m.EndTime.ToString("yyyy-MM-dd"),
                   Code = m.Code
               };
            ViewBag.Customers = GetCustomers();
           return View(contract); 
        }

        /// <summary>
        /// 修改合同 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Edit(int id, ContractViewModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var entity = _query.Get<Contract>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }  
                    entity.Modified = DateTime.Now; 
                    entity.BeginTime =DateTime.Parse( model.BeginTime);
                    entity.EndTime =DateTime.Parse( model.EndTime);
                    var customer = _query.Get<Subsidiary>(model.Customer);
                    if (null == customer)
                    {
                        ModelState.AddModelError("Customer", "客户不存在,请重新选择");
                        ViewBag.Customers = GetCustomers();
                        return View();
                    }
                    entity.Subsidiary = customer; 
                    _query.Save(entity); 
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            ViewBag.Customers = GetCustomers();
            return View();
        }

        [Transaction]
        [HttpGet]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<Contract>(id);

            if (null == entity)
            {
                return View("NoFound");
            } 
            entity.Stauts= DataStatus.Deleted;
            _query.Save(entity);
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index");
            }
            return Redirect(returnUrl);
        }
    }
}
